/**
 * Copyright HCP Technology 
 * www.hcp.vn
 */
package controllers;

import java.util.ArrayList;
import java.util.List;

import models.CategoryNode;
import models.ContentModel;
import play.Logger;
import play.data.validation.Required;
import util.PaginationInfo;
import util.SimpleCache;
import util.Util;

public class Category extends Application {
	
	public static void index(@Required String alias, int page){
		System.out.println("alias >> " + alias);
		System.out.println("page >> " + page);
		
		CategoryNode category = SimpleCache.findCategory(alias, 0);
		
		if(category == null){
			renderTemplate(Util.ERROR_404);
		}
		List<ContentModel> listContentModels = null;
		if(page == 0){
			page = 1;
		}
		List<ContentModel> listContentModelTotals = SimpleCache.listContentModel(category.alias);
		listContentModels = getListContentLimit(listContentModelTotals, page, Util.PAGE_ITEM);
		Logger.info("fetchContents >> " + listContentModels.size());
		int total = listContentModelTotals.size();
		Logger.info("total >> " + total);
		// page = 2;
		String action = "/xem-chu-de/" + alias;
		PaginationInfo paginationInfo = new PaginationInfo(
				action, // action]
				null,
				page, // current page
				Util.PAGE_ITEM, // items per page
				total // total number of results
				// query params to be included in the links
		);
		//paginationInfo.alias = action;
		render(listContentModels, paginationInfo);
	}

	private static List<ContentModel> getListContentLimit(List<ContentModel> listContentModelTotals, int page, int limit){
		List<ContentModel> rs = new ArrayList<ContentModel>();
		for(int i = (page - 1)* limit; i<page*limit; i++){
			if(i < listContentModelTotals.size()){
				rs.add(listContentModelTotals.get(i));	
			}
		}
		return rs;
	}
	
	/*public static void getNameCategory(){
		Logger.info("test");
		String name = CategoryEnum.valueOf("1").name();
		renderText(name);
	}*/
}
